const db = require("../db");
const bcrypt = require("bcryptjs/dist/bcrypt");
// 获取用户信息
exports.getUserInfo = (req, res) => {
  const sql =
    "select id,username,nickname,email,user_pic,roles from ev_users where id = ?";
    // 当登录成功后，jwt会自动在req上挂载一个user
  db.query(sql, req.user.id, (err, results) => {
    console.log(results[0]);
    if (err) return res.cc(err.message);
    if (results.length !== 1) return res.cc("获取用户信息失败");
    res.send({
      status: 200,
      message: "获取用户基本信息成功",
      data: results[0],
    });
  });
};
// 更新用户信息
exports.updateUserInfo = (req, res) => {
  const sql = "update ev_users set ? where id = ?";
  db.query(sql, [req.body, req.body.id], (err, result) => {
    if (err) return res.cc(err.message);
    if (result.affectedRows !== 1) return res.cc("更新用户信息失败");
    res.cc("更新用户信息成功", 200);
  });
};
// 更新密码
exports.resetPassword = (req, res) => {
  const sql = "select password from ev_users where id = ?";
  db.query(sql, req.user.id, (err, results) => {
    if (err) return res.cc(err.message);
    if (results.length !== 1) return res.cc("用户不存在");
    // 判断提交的旧密码是否正确
    const comparseRes = bcrypt.compareSync( 
      req.body.oldPassword,
      results[0].password
    );
    if (!comparseRes) return res.cc("旧密码错误");
    // 对新密码进行加密并更新
    const updatePwdSql = 'update ev_users set password = ? where id = ?'
    const newPwd = bcrypt.hashSync(req.body.newPassword,10)
    db.query(updatePwdSql,[newPwd,req.user.id],(err,results) => {
      if(err) return res.cc(err.message)
      if(results.affectedRows !== 1) return res.cc('更新密码失败')
      res.cc('跟新密码成功',200)
    })
  });
};

exports.updateAvatar = (req,res) => {
  const sql = 'update ev_users set user_pic = ? where id = ?'
  db.query(sql,[req.body.user_pic,req.user.id],(err,results) => {
    if(err) return res.cc(err.message)
    if(results.affectedRows !==1) return res.cc('修改头像失败')
    res.cc('修改头像成功',200)
  })
}